<?php
/**
 * 订单相关
 *
 * Author:李强
 * Company:上海煦鸣网络科技有限公司
 * Date:2018-01-03
 */

namespace App\Http\Controllers\Admin;


use App\Models\BlackAccount;
use App\Models\Config;
use App\Models\Order;
use App\Models\Shop;
use App\Services\Service\Helper;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;

class OrderController extends BaseController
{
    //
    public function __construct()
    {
        $shops = Shop::where(['status' => 1])->get();
        $this->assign('shops', $shops);
    }

    public function index(Request $request)
    {
        //
        $inputs = Helper::getInputs($request, ['opt_type' => '', 'keywords' => '', 'page' => 1, 'limit' => 10, 'status' => '', 'type' => '', 't' => 0, 'pay_status' => '']);

        $page = intval($inputs['page']);
        $limit = intval($inputs['limit']);
        $start = ($page - 1) * $limit;

        $where = [];
        $where['normal'][] = [];
        if ($inputs['t']) {
            $status = $inputs['t'] - 1;
            $where['where'][] = ['status' => $status];
        }
        if ($inputs['opt_type'] != '' && $inputs['keywords'] != '') {
            if (in_array($inputs['opt_type'], ['shop_id', 'user_id', 'account_no', 'item_id'])) {
                $where['where'][] = [$inputs['opt_type'] => $inputs['keywords']];
            } else if (in_array($inputs['opt_type'], ['nickname'])) {
                $where['whereHas'][] = ['user', function ($query) use ($inputs) {
                    $query->where($inputs['opt_type'], 'like', '%' . $inputs['keywords'] . '%');
                }];
            } else {
                $where['where'][] = [$inputs['opt_type'], 'like', '%' . $inputs['keywords'] . '%'];
            }
        }
        if ($inputs['status'] != '') {
            $where['where'][] = ['status' => $inputs['status']];
        }
        if ($inputs['type'] != '') {
            $where['where'][] = ['type' => $inputs['type']];
        }
        if ($inputs['pay_status'] != '') {
            $where['where'][] = ['pay_status' => $inputs['pay_status']];
        }
        $result = Order::queryAll($where, [['created_at', 'desc']], [$start, $limit]);
        $result['conditions'] = $inputs;
        return $this->display('order.index', $result);
    }

    /**
     * 查看订单详情
     *
     * @param Request $request
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function show(Request $request, $id)
    {
        $order = Order::find($id);
        $this->assign('vo', $order);
        return $this->display('order.show');
    }

    /**
     * 新增订单
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function create(Request $request)
    {
        return $this->display('order.create');
    }

    /**
     * 账号校验
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function check(Request $request)
    {
        if ($request->ajax() && $request->method('post')) {
            $shop_id = $request->input('shop_id', 0);
            $account_no = $request->input('account_no', '');
            //判断是否存在黑名单
            $count = BlackAccount::where(['is_delete'=>0,'account_no'=>$account_no])->count();
            if($count>0){
                return $this->error('账号:'.$account_no.'已被列入黑名单', 0, ['tiptype' => 0]);
            }
            $result = Order::check($account_no, $shop_id);
            if (empty($result)) {
                return $this->success('success');
            } else {
                $tiptype = Config::getConfig('tiptype', 1);
                $message = "";
                if (isset($result['interval'])) {
                    $message .= "同店铺下" . $result['interval']['days'] . '天内已补单' . $result['interval']['count'] . '笔<br/>';
                }
                if (isset($result['interval_diff'])) {
                    $message .= "不同店铺下" . $result['interval_diff']['days'] . '天内已补单' . $result['interval_diff']['count'] . '笔<br/>';
                }
                if ($message == '') {
                    return $this->success('success');
                }
                if ($message != '') {
                    $message = '<font color="red">' . $message . '</font>';
                }
                if ($tiptype == 1 && $message != '') {
                    $message .= "是否继续？";
                }
                return $this->error($message, 0, ['tiptype' => $tiptype]);
            }
        }
    }

/**
 * 订单新增处理
 *
 * @param Request $request
 * @return \Illuminate\Http\JsonResponse
 */
public
function store(Request $request)
{
    if ($request->ajax()) {
        $shop_id = $request->input('shop_id', '');
        if (!$shop_id) {
            return $this->error('请选择店铺');
        }
        $price = $request->input('price', 0);
        if (!$price) {
            return $this->error('填写宝贝价格');
        }
        $commission = $request->input('commission', 0);
        if (!$commission) {
            return $this->error('填写佣金');
        }
        $account_no = $request->input('account_no', 1);
        if ($account_no == '') {
            return $this->error('请填写买家账号');
        }
        $order_no = $request->input('order_no', '');
        if ($order_no == '') {
            return $this->error('填写订单编号');
        }
        if (Order::isExist($order_no)) {
            return $this->error('订单编号已经存在');
        }
        $order_time = $request->input('order_time', '');
        if ($order_no == '') {
            return $this->error('填写订单时间');
        }
        $order = new Order();
        $order->shop_id = $shop_id;//店铺ID
        $order->iid = $request->input('iid', 0);
        $order->item_id = $request->input('item_id', '');
        $order->item_title = $request->input('item_title', '');
        $order->price = $price;
        $order->commission = $commission;
        $order->account_id = 0;
        $order->account_no = $account_no;
        $order->user_id = Auth::id();
        $order->order_no = $order_no;
        $order->order_time = $order_time;
        $order->status = 4;
        $order->money_sj = $request->input('money_sj', 0);
        $order->commission_sj = $request->input('commission_sj', 0);
        $order->comm = $request->input('comm', '');
        $order->source = 1;
        if (false !== $order->save()) {
            return $this->success('新增成功', ['redirect' => url('order')]);
        } else {
            return $this->error('新增失败');
        }
    }
}

/**
 * 订单编辑
 *
 * @param Request $request
 * @param $id
 */
public
function edit(Request $request, $id)
{
    $order = Order::find($id);
    $this->assign('vo', $order);
    return $this->display('order.edit');
}

/**
 * 订单编辑更新
 *
 * @param Request $request
 * @param $id
 */
public
function update(Request $request, $id)
{
    if ($request->ajax()) {
        $order = Order::find($id);
        if (is_null($order)) {
            return $this->error('查询订单失败');
        }
        $price = $request->input('price', 0);
        if (!$price) {
            return $this->error('填写宝贝价格');
        }
        $commission = $request->input('commission', 0);
        if (!$commission) {
            return $this->error('填写佣金');
        }
        $order_no = $request->input('order_no', '');
        if ($order_no == '') {
            return $this->error('填写订单编号');
        }
        if (Order::isExist($order_no, $id)) {
            return $this->error('订单编号已经存在');
        }
        $order_time = $request->input('order_time', '');
        if ($order_no == '') {
            return $this->error('填写订单时间');
        }
        $order->item_id = $request->input('item_id', '');
        $order->item_title = $request->input('item_title', '');
        $order->price = $price;
        $order->commission = $commission;
        $order->order_no = $order_no;
        $order->order_time = $order_time;
        $order->money_sj = $request->input('money_sj', 0);
        $order->commission_sj = $request->input('commission_sj', 0);
        $order->comm = $request->input('comm', '');
        if (false !== $order->save()) {
            return $this->success('更新成功', ['redirect' => url('order')]);
        } else {
            return $this->error('更新失败');
        }
    }
}

/**
 * 订单删除
 *
 * @param Request $request
 * @param $id
 * @return \Illuminate\Http\JsonResponse
 */
public
function destroy(Request $request, $id)
{
    if ($request->ajax()) {
        $order = Order::find($id);
        if (is_null($order)) {
            return $this->error('查询订单信息失败');
        }
        if (false !== $order->delete()) {
            return $this->success('删除成功');
        } else {
            return $this->error('删除失败');
        }
    }
}

/**
 * 数据导入
 *
 * @param Request $request
 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
 */
public
function import(Request $request)
{
    if ($request->ajax() && $request->isMethod('post')) {
        if ($request->input('submit', 0)) {//做导入处理
            $shop_id = $request->input('shop_id', 0);
            $shop = Shop::find($shop_id);
            if (is_null($shop)) {
                return $this->error('查询店铺信息出错');
            }
            $datas = $request->input('data', []);
            if (empty($datas)) {
                return $this->error('数据不能为空');
            }
            $result = [];
            $error = 0;
            $errors = [];
            foreach ($datas as $key => $data) {
                //校验订单编号是否已经存在
                $tip = '第' . ($key + 2) . '行数据';
                $err_message = [];
                $order_no = $data['order_no'];
                $account_no = $data['account_no'];
                $order_time = $data['order_time'];
                $price = $data['price'];
                $commission = $data['commission'];
                if ($account_no == '') {
                    $err_message[] = '买家账号不能为空';
                }
                if ($order_time == '') {
                    $err_message[] = '订单时间不能为空';
                }
                if (Order::isExist($order_no)) {
                    $err_message[] = '订单编号已存在';
                }
                if ($price <= 0) {
                    $err_message[] = '宝贝价格应大于0';
                }
                if ($commission < 0) {
                    $err_message[] = '佣金不能小于0';
                }
                if (!empty($err_message)) {
                    $errors[] = $tip . implode(' ', $err_message);
                    continue;
                }
                $data['shop_id'] = $shop_id;
                $data['money_sj'] = $price + $commission;
                $data['commission_sj'] = $commission;
                $data['source'] = 2;
                $data['status'] = 4;
                if (false !== Order::create($data)) {
                    continue;
                } else {
                    $errors[] = $tip . '数据新增失败';
                }
            }
            $message = "共:" . count($datas) . '条数据,其中失败:' . count($errors);
            return $this->success($message, ['error' => count($errors), 'errors' => $errors]);
        } else {//导入文件反馈数据
            if (!$request->hasFile('file')) {
                return $this->error('上传文件为空！');
            }
            $file = $_FILES;
            $excel_file_path = $file['file']['tmp_name'];
            $res = [];
            $header = [
                ['order_time', 'datetime'],
                ['order_no', 'string'],
                ['account_no', 'string'],
                ['item_id', 'string'],
                ['item_title', 'string'],
                ['price', 'float'],
                ['commission', 'float'],
                ['user_id', 'int'],
                ['comm', 'string']
            ];
            Excel::load($excel_file_path, function ($reader) use (&$res) {
                $reader = $reader->getSheet(0);//excel第一张sheet
                $res = $reader->toArray();
                //去除第一行
                array_shift($res);
            });
            $datas = [];
            if (!empty($res)) {
                $first = $res[0];
                if (count($first) != count($header)) {
                    return $this->error('表格列数错误');
                }
                foreach ($res as $data) {
                    $temp = [];
                    foreach ($header as $key => $head) {
                        $type = isset($head[1]) ? $head[1] : 'string';
                        $field_name = $head[0];
                        switch ($type) {
                            case 'float':
                                $temp[$field_name] = @floatval($data[$key]);
                                break;
                            case 'int':
                                $temp[$field_name] = @intval($data[$key]);
                                break;
                            case 'datetime':
                                $temp[$field_name] = Helper::toDate(strtotime($data[$key]));
                                break;
                            default:
                                $temp[$field_name] = $data[$key];
                                break;
                        }
                    }
                    $datas[] = $temp;
                }
            }
            return $this->success('success', $datas);
        }
    }
    return $this->display('order.import');
}
}
